﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Collider), typeof(Rigidbody))]
public class AvoidHorizontal : MonoBehaviour {

    public float m_speed = 1f;
    public Animator m_animator;
    public IJoyStick joyStick;

    private Collider _collider;
    private Collider _otherCollider;
    private Rigidbody _rigidBoddy;
    private bool _avoiding;
    private Vector3 _avoidDirection;//前进却被挡住，往某方向横向移动（取决于撞击位置与中心点的距离）
    private Vector3 _goingDirection;//记录进入avoiding动作的时候前进的方向

    void Start () {
        _collider = GetComponent<Collider>();
        _rigidBoddy = GetComponent<Rigidbody>();
    }
	
	void Update () {
        //障碍物被摧毁了，就取消掉avoid动作
        if(_avoiding && _otherCollider==null)
        {
            //Debug.Log("OtherCollider gone, cancel avoiding");
            _avoiding = false;
            m_animator.SetBool("avoiding", false);
        }

        if(_avoiding && _goingDirection != joyStick.coarseDirection)
        {
            //Debug.Log("input a different direction, cancel avoiding");
            _avoiding = false;
            m_animator.SetBool("avoiding", false);
        }

        if (_avoiding && joyStick.inputMoveVal>0)
        {
            Move(_avoidDirection);
        }
	}

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag != "Obstacle")
        {
            return;
        }
        //Debug.Log("normal=" + collision.contacts[0].normal+", joyStickDir="+ joyStick.getCoarseDirection());

        if (_otherCollider != null) return;

        //撞击的方向跟控制的方向不是正好相反，则不属于要回避的情况
        if (collision.contacts[0].normal != joyStick.coarseDirection)
        {
            //Debug.Log("different direction between collistion and input, not avoiding");
            return;
        }
        
        //开始撞击后的横向移动
        startAvoiding(collision);
    }

    private void OnCollisionExit(Collision collision)
    {
        if (collision.collider.tag != "Obstacle")
        {
            return;
        }

        if(_otherCollider==collision.collider)
        {
            _otherCollider = null;
        }

        _avoiding = false;
        m_animator.SetBool("avoiding", false);


    }

    //TODO 连续碰到不同角度的墙，例如90度的墙角会发生停止移动的状况，待解决
    private void OnCollisionStay(Collision collision)
    {
        if (collision.collider.tag != "Obstacle")
        {
            return;
        }

        //Debug.Log("OnCollisionStay "+collision.contacts[0].point);

        //还处于紧贴状态，avoiding因为改了方向而被取消了，但又重新回到前进的方向，则avoid要恢复
        if(!_avoiding && joyStick.coarseDirection==_goingDirection)
        {
            startAvoiding(collision);
        }
    }

    private void Move(Vector3 direction)
    {
        float moveInput = joyStick.inputMoveVal;
        Vector3 movement = direction * moveInput * m_speed * Time.deltaTime;
        //_rigidBoddy.MovePosition(_rigidBoddy.position + movement);
        transform.position = transform.position + movement;
    }

    //根据撞击的位置判断该往哪边横移，同时触发动画播放
    //如果撞到的位置是障碍物中心点的右侧，则往障碍物的右侧横移，反之亦然
    private void startAvoiding(Collision collision)
    {
        _otherCollider = collision.collider;
        _goingDirection = collision.contacts[0].normal;

        _avoiding = true;
        m_animator.SetBool("avoiding", true);

        //foreach (ContactPoint c in collision.contacts)
        //{
        //    Debug.DrawRay(c.point, c.normal, Color.white, 10f);
        //    //Debug.Log("collision point=" + c.point + ", locate point=" + transform.position
        //    //    + ", normal=" + c.normal);

        //}

        ContactPoint contact = collision.contacts[0];
        Debug.DrawLine(contact.otherCollider.bounds.center, transform.position, Color.red, 3f);

        if (contact.normal == Vector3.forward)
        {
            float otherX = contact.otherCollider.bounds.center.x;
            if (otherX > transform.position.x)
            {
                _avoidDirection = Vector3.left;
                m_animator.SetTrigger("avoidingLeft");
            }
            else
            {
                _avoidDirection = Vector3.right;
                m_animator.SetTrigger("avoidingRight");
            }
            //Debug.Log("up=" + _avoidDirection);
        }
        else if (contact.normal == Vector3.back)
        {
            float otherX = contact.otherCollider.bounds.center.x;
            if (otherX > transform.position.x)
            {
                _avoidDirection = Vector3.left;
                m_animator.SetTrigger("avoidingRight");
            }
            else
            {
                _avoidDirection = Vector3.right;
                m_animator.SetTrigger("avoidingLeft");
            }
            //Debug.Log("down=" + _avoidDirection);
        }
        else if (contact.normal == Vector3.left)
        {
            float otherZ = contact.otherCollider.bounds.center.z;
            if (otherZ > transform.position.z)
            {
                _avoidDirection = Vector3.back;
                m_animator.SetTrigger("avoidingRight");
            }
            else
            {
                _avoidDirection = Vector3.forward;
                m_animator.SetTrigger("avoidingLeft");
            }
            //Debug.Log("left=" + _avoidDirection);

        }
        else if (contact.normal == Vector3.right)
        {
            float otherZ = contact.otherCollider.bounds.center.z;
            if (otherZ > transform.position.z)
            {
                _avoidDirection = Vector3.back;
                m_animator.SetTrigger("avoidingLeft");
            }
            else
            {
                _avoidDirection = Vector3.forward;
                m_animator.SetTrigger("avoidingRight");
            }
            //Debug.Log("right=" + _avoidDirection);
        }
    }
}
